package models

import (
	"fmt"
	"golang-blog/infrastructure/databases"
	"golang-blog/infrastructure/log"
	"math/rand"
	"time"
)

func DBMigration(tables []interface{}) {
	rand.Seed(time.Now().UnixNano())
	dua := time.Duration(rand.Int63n(time.Now().UnixNano()) % 10)
	dua = dua * time.Second
	log.Infof("延时%vs. 等待创建数据表 ...%v", dua.Seconds(), time.Now())
	time.Sleep(dua)
	log.Infof("开始创建数据表 ...%v", time.Now())

	database := databases.GetDB()
	if database == nil {
		panic("初始化数据库失败")
	}
	tx := database.Begin()
	if tx == nil {
		panic("连接数据库失败")
	}

	for _, table := range tables {
		err := tx.AutoMigrate(table)
		if err != nil {
			tx.Callback()
			panic(fmt.Sprintf("数据库创建失败:%v\n", err))
		}
	}

	tx.Commit()

	log.Info("数据表创建成功 ！！！")
}

func TableExist(tableName string) (isExist bool) {
	database := databases.GetDB()

	isExist = database.Debug().Migrator().HasTable(tableName)
	log.Infof("数据库表: %v 是否存在: %v,", tableName, isExist)

	return
}
